package netty.dubboRPC.netty;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import netty.dubboRPC.provider.HelloServiceImpl;

/**
 * @ClassName NettyServerHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/5/18 13:31
 * @Version 1.0
 **/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //获取客户端发送的消息，并调用

        System.out.println("NettyServerHandler中，收到的msg="+msg);

        /**客户端再调用服务端api时候，需要定义一个协议
         * 比如我们要求：每次发消息时，都必须以某个字符串开头 ‘HelloService#’
         * 实际项目中，还是以定义的协议体，或者变量，来作为协议判定
         */

        if (msg.toString().startsWith("HelloService#Hello#")){

            String hello = new HelloServiceImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(hello);

        }



    }
}
